package com.chenc.unitdemo.jwt.controller;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chenc.unitdemo.jwt.dto.UserDto;
import com.chenc.unitdemo.jwt.dto.UserLoginDto;
import com.chenc.unitdemo.jwt.entity.User;
import com.chenc.unitdemo.jwt.golbal.BusinessException;
import com.chenc.unitdemo.jwt.golbal.ControllerBase;
import com.chenc.unitdemo.jwt.golbal.Result;
import com.chenc.unitdemo.jwt.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @ClassName
 * @Describtion:
 * @Author:Chenc
 * @Date:2024/1/3 17:16
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController extends ControllerBase{

    @Autowired
    private IUserService userService;

    //创建用户
    @PostMapping("/registerSelf")
    public UserDto createUserSelf(@RequestBody UserDto userDto){

        userService.checkuser(userDto);
        userService.saveDto(userDto);
        UserLoginDto build = UserLoginDto.builder().password(userDto.getPassword()).username(userDto.getUsername()).build();
        userService.checkPwd(build);
        return userDto;
    }
    @PostMapping("/registerManage")
    public UserDto createUserManage(@RequestBody UserDto userDto){
        userDto.setPassword("12346578Aa");
        userService.checkuser(userDto);
        userService.saveDto(userDto);
        return userDto;
    }

    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody UserDto userDto){
        String pwd = "12346578Aa";
        if (StringUtils.isEmpty(userDto.getUsername())){
            throw new BusinessException("用户名必输");
        }
        Long count = userService.count(new LambdaQueryWrapper<User>().eq(User::getUsername, userDto.getUsername()));
        if (count.compareTo(0L)<=0){
            throw new BusinessException("该用户名还没有注册 请先注册");
        }
        String hashpw = BCrypt.hashpw(pwd);
        userService.update(new LambdaUpdateWrapper<User>().eq(User::getUsername,userDto.getUsername()).set(User::getPwd,hashpw));
        return ok(pwd);
    }

    @PostMapping
    public UserLoginDto login(@Valid @RequestBody UserLoginDto userLoginDto){
        //验证密码是否正确
        userService.checkPwd(userLoginDto);
        userService.convertToken(userLoginDto);
        return userLoginDto;
    }


}
